package com.github.permissiondog.cancanpandroid.repository.impl;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.github.permissiondog.cancanpandroid.MyApplication;
import com.github.permissiondog.cancanpandroid.repository.ImageRepository;
import com.github.permissiondog.cancanpandroid.repository.api.ResourceApiService;
import com.github.permissiondog.cancanpandroid.repository.api.response.UploadResourceResponse;
import com.github.permissiondog.cancanpandroid.util.CallBack;
import com.github.permissiondog.cancanpandroid.util.NetUtil;

import java.io.ByteArrayOutputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ImageRepositoryImpl implements ImageRepository {
    private static ImageRepository INSTANCE;
    public static synchronized ImageRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new ImageRepositoryImpl();
        }
        return INSTANCE;
    }
    private final ResourceApiService resourceApiService;
    private ImageRepositoryImpl() {
        this.resourceApiService = NetUtil.RETROFIT.create(ResourceApiService.class);
    }

    @Override
    public void uploadImage(Bitmap image, CallBack<UploadResourceResponse> res) {
        var stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, stream);
        var requestBody = RequestBody.create(MediaType.parse("image/png"), stream.toByteArray());
        var body = MultipartBody.Part.createFormData("file", "image.png", requestBody);
        resourceApiService.uploadResource(body).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<UploadResourceResponse> call, Response<UploadResourceResponse> response) {
                if (!response.isSuccessful() || response.body() == null) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "网络错误", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!response.body().isOk()) {
                    Toast.makeText(MyApplication.getInstance().getApplicationContext(), "上传图片失败", Toast.LENGTH_LONG).show();
                    return;
                }
                res.callback(response.body());
            }

            @Override
            public void onFailure(Call<UploadResourceResponse> call, Throwable t) {
                Log.w("request", "上传图片失败", t);
            }
        });
    }
}
